1) 가급적 주어진 스켈레톤 코드를 활용하였습니다.
2) cv2.imshow를 하면 jupyter상에서는 또 다른 화면으로 출력되어서 matplotlib으로 이미지를 보기 편하게 병합하였습니다.
1‐1. Translation, Rotation, Similarity Transformation 행렬을 구성하고, OpenCV Library의 cv2.warpAffine 함수를 이용하여 임의의 이미지에 적용해 변형해보시오.
import cv2
import numpy as np
from matplotlib import pyplot as plt
src = cv2.imread("ramjui.jpg", cv2.IMREAD_GRAYSCALE)
rows, cols = src.shape
image는 Grayscale로 적용하였습니다.
마지막 median Blur에서 channel이 3인 경우를 처리할때, 제 코드에서 sort 에러가 발생하는데 이를 처리하지 못했기 때문입니다.
이 점 양해부탁드립니다.
def translate(image, x, y):
translation_matrix = np.float32([[1,0,150],[0,1,75]])
transformed_image = cv2.warpAffine(src, translation_matrix,(cols,rows))
return transformed_image
def rotate(image, angle):
translation_matrix = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
transformed_image = cv2.warpAffine(src, translation_matrix, (rows, cols))
return transformed_image
def similarity(image, x, y, angle): #TODO:scale
translation_matrix = cv2.getRotationMatrix2D((30, 100),angle, 1)
transformed_image = cv2.warpAffine(src, translation_matrix, (cols, rows))
return transformed_image
plt.figure(figsize=(20,5))
plt.subplot(1,4,1), plt.imshow(src), plt.title("original")
plt.subplot(1,4,2), plt.imshow(translate(src,rows,cols)), plt.title("shifted_right 150, shifted_height 75")
plt.subplot(1,4,3), plt.imshow(rotate(src, 270)), plt.title("rotate 270")
plt.subplot(1,4,4), plt.imshow(similarity(src,rows,cols,30)), plt.title("similarity transformation")
(<AxesSubplot:title={'center':'similarity transformation'}>,
<matplotlib.image.AxesImage at 0x1c8d8837f40>,
Text(0.5, 1.0, 'similarity transformation'))
def average_image(image):
filter = np.ones((50,50), np.float32) / 2500
result = cv2.filter2D(image, -1, filter)
return result
def sharpen_image(image):
kernel_size = [50]
kernel_list = []
for i in kernel_size:
temp_list = np.zeros((i,i), np.float32)
temp_list[i//2, i//2] = 2
kernel_list.append(temp_list - np.ones((i,i),np.float32)/(i*i))
result = cv2.filter2D(image, -1, kernel_list[0])
return result
plt.figure(figsize=(20,6))
plt.subplot(1,4,1), plt.imshow(src), plt.title('original')
plt.subplot(1,4,2), plt.imshow(average_image(src)),plt.title('average')
plt.subplot(1,4,3), plt.imshow(sharpen_image(src)),plt.title('shapen')
(<AxesSubplot:title={'center':'shapen'}>,
<matplotlib.image.AxesImage at 0x1c8d8559730>,
Text(0.5, 1.0, 'shapen'))
Sharpening Filter도 역시 Kenrnel의 사이즈 결정해야합니다.
Kernel은 중앙에 위치한 행렬의 요소가 2인 행렬(Kernel과 동일한 사이즈이며,
1이면 원본과 동일한 이미지, 2이면 강조된 이미지)에서 모든 요소가 1/mean인 Kernel로 빼주면 됩니다.
이렇게 되면 가운데는 더욱 부각되고 나머지는 덜 부각시킴으로써 경계선 부근이 더욱 부각되도록 하는 효과를 줍니다.
def Gaussian_blur(image):
kernel_gaussian_1d = cv2.getGaussianKernel(5, 3)
#size가 5고 sigma가 3인 커널을 생성
kernel_gaussian_2d = np.outer(kernel_gaussian_1d, kernel_gaussian_1d.transpose())
filter = cv2.filter2D(image, -1, kernel_gaussian_2d)
return filter
plt.figure(figsize=(20,6))
plt.subplot(1,4,1), plt.imshow(Gaussian_blur(src)),plt.title('gaussian blur')
(<AxesSubplot:title={'center':'gaussian blur'}>,
<matplotlib.image.AxesImage at 0x1c8d8afd520>,
Text(0.5, 1.0, 'gaussian blur'))
import copy
import random
def add_salt_pepper_noise(image, prob):
img_Salt_Pepper = np.zeros(image.shape, np.uint8) # uint8 : 0~255 표현
for i in range(image.shape[0]): # height
for j in range(image.shape[1]): # width
var1_rdn = random.random() # 0~1 사이의 random한 실수 생성
if var1_rdn < prob: # salt 생성
img_Salt_Pepper[i][j] = 0
elif var1_rdn > (1 - prob): # pepper salt랑 pepper 동일 밀도로 하기위해 1-prob한다
img_Salt_Pepper[i][j] = 255
else:
img_Salt_Pepper[i][j] = image[i][j]
return img_Salt_Pepper
plt.figure(figsize=(20,4))
plt.subplot(1,4,1), plt.imshow(add_salt_pepper_noise(src, 0.01)),plt.title('add_salt_pepper_noise')
plt.subplot(1,4,2), plt.imshow(add_salt_pepper_noise(src, 0.05)),plt.title('add_salt_pepper_noise')
plt.subplot(1,4,3), plt.imshow(add_salt_pepper_noise(src, 0.10)),plt.title('add_salt_pepper_noise')
plt.subplot(1,4,4), plt.imshow(add_salt_pepper_noise(src, 0.15)),plt.title('add_salt_pepper_noise')
#적용한 pepper에 애버리지, 샤프닝, 가우시안을 적용한다.
plt.figure(figsize=(20,3))
plt.subplot(1,4,1), plt.imshow(average_image(add_salt_pepper_noise(src, 0.15))),plt.title('average with pepper 0.15')
plt.subplot(1,4,2), plt.imshow(sharpen_image(add_salt_pepper_noise(src, 0.15))),plt.title('sharpen with pepper 0.15')
plt.subplot(1,4,3), plt.imshow(Gaussian_blur(add_salt_pepper_noise(src, 0.15))),plt.title('gaussian with pepper 0.15')
(<AxesSubplot:title={'center':'gaussian with pepper 0.15'}>,
<matplotlib.image.AxesImage at 0x1c8d8c991f0>,
Text(0.5, 1.0, 'gaussian with pepper 0.15'))
def median_blur(image):
pepper = add_salt_pepper_noise(src,0.2) #salt 0.2 가 적용된 이미지
filter = cv2.medianBlur(pepper, 3)
return filter
plt.figure(figsize=(20,6))
plt.subplot(1,4,1), plt.imshow(median_blur(src)),plt.title('pepper with median_blur')
plt.subplot(1,4,2), plt.imshow(add_salt_pepper_noise(src,0.2)),plt.title('pepper')
(<AxesSubplot:title={'center':'pepper'}>,
<matplotlib.image.AxesImage at 0x1c8d8e44790>,
Text(0.5, 1.0, 'pepper'))
down_result_01 = cv2.resize(src, None, fx=0.3, fy=0.3, interpolation=cv2.INTER_AREA)
down_result_02 = cv2.resize(src, None, fx=0.3, fy=0.3, interpolation=cv2.INTER_NEAREST)
down_result_03 = cv2.resize(src, None, fx=0.3, fy=0.3, interpolation=cv2.INTER_LINEAR)
down_result_04 = cv2.resize(src, None, fx=0.3, fy=0.3, interpolation=cv2.INTER_CUBIC)
up_result_01 = cv2.resize(down_result_01, None, fx=2, fy=2, interpolation=cv2.INTER_AREA)
up_result_02 = cv2.resize(down_result_02, None, fx=2, fy=2, interpolation=cv2.INTER_NEAREST)
up_result_03 = cv2.resize(down_result_03, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
up_result_04 = cv2.resize(down_result_04, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
plt.figure(figsize=(20,10))
plt.subplot(2,5,1),plt.imshow(src),plt.title('Original')
plt.subplot(2,5,2),plt.imshow(down_result_01),plt.title('inter area')
plt.subplot(2,5,3),plt.imshow(down_result_02),plt.title('inter nearest')
plt.subplot(2,5,4),plt.imshow(down_result_03),plt.title('inter linear')
plt.subplot(2,5,5),plt.imshow(down_result_04),plt.title('inter cubic')
plt.subplot(2,5,6),plt.imshow(src),plt.title('Original')
plt.subplot(2,5,7),plt.imshow(up_result_01),plt.title('INTER_AREA')
plt.subplot(2,5,8),plt.imshow(up_result_02),plt.title('INTER_NEAREST')
plt.subplot(2,5,9),plt.imshow(up_result_03),plt.title('INTER_LINEAR')
plt.subplot(2,5,10),plt.imshow(up_result_04),plt.title('INTER_CUBIC')
(<AxesSubplot:title={'center':'INTER_CUBIC'}>,
<matplotlib.image.AxesImage at 0x1c8dc1e7220>,
Text(0.5, 1.0, 'INTER_CUBIC'))
def Gaussian_Pyramid(img, number):
down_sampling = []
img_shape = []
temp_img = img.copy()
down_sampling.append(temp_img)
img_shape.append(temp_img.shape)
for i in range(number):
temp_down = cv2.pyrDown(temp_img)
down_sampling.append(temp_down)
img_shape.append(temp_down.shape)
temp_img = temp_down
return down_sampling
down_sampling = Gaussian_Pyramid(src, 3)
plt.figure(figsize=(20,15))
plt.subplot(2,4,1),plt.imshow(down_sampling[0])
plt.subplot(2,4,2),plt.imshow(down_sampling[1]),plt.xlim(0,down_sampling[0].shape[1]),plt.ylim(down_sampling[0].shape[0],0)
plt.subplot(2,4,3),plt.imshow(down_sampling[2]),plt.xlim(0,down_sampling[0].shape[1]),plt.ylim(down_sampling[0].shape[0],0)
plt.subplot(2,4,4),plt.imshow(down_sampling[3]),plt.xlim(0,down_sampling[0].shape[1]),plt.ylim(down_sampling[0].shape[0],0)
cv2.imwrite('ranjui_py1.jpg', down_sampling[1])
cv2.imwrite('ranjui_py2.jpg', down_sampling[2])
cv2.imwrite('ranjui_py3.jpg', down_sampling[3])
True
def my_median_blur(data, filter_size):
temp = []
indexer = filter_size // 2
data_final = []
data_final = np.zeros((len(data),len(data[0])))
for i in range(len(data)):
for j in range(len(data[0])):
for z in range(filter_size):
if i + z - indexer < 0 or i + z - indexer > len(data) - 1:
for c in range(filter_size):
temp.append(0)
else:
if j + z - indexer < 0 or j + indexer > len(data[0]) - 1:
temp.append(0)
else:
for k in range(filter_size):
temp.append(data[i + z - indexer][j + k - indexer])
temp.sort()
data_final[i][j] = temp[len(temp) // 2]
temp = []
return data_final
def apply_my_blur(image):
pepper = add_salt_pepper_noise(src,0.2)
result = my_median_blur(pepper, 3)
return result
plt.figure(figsize=(20,6))
plt.subplot(1,4,1), plt.imshow(add_salt_pepper_noise(src,0.2)),plt.title('pepper')
plt.subplot(1,4,2), plt.imshow(median_blur(src)),plt.title('pepper with median_blur')
plt.subplot(1,4,3), plt.imshow(apply_my_blur(src)),plt.title('pepper with my_median_blur')
(<AxesSubplot:title={'center':'pepper with my_median_blur'}>,
<matplotlib.image.AxesImage at 0x1c8dc5edbe0>,
Text(0.5, 1.0, 'pepper with my_median_blur'))
assignment guide에 따라서 sort를 사용하는데, 채널이 3일 경우 (color image일 경우)
temp.sort에서 에러가 나는 현상이 있었고
color image에 맞는 (channel이 3인 경우)는 구현을 하지 못했습니다.
그래서 회색조 이미지로 컨버팅했습니다.